subtract-the-product-and-sum-of-digits-of-an-integer
Given an integer number n, return the difference between the product of its digits and the sum of its digits.
給定一個正整數 n
回傳 n的每個digit相乘 減去 n的每個digit相加的結果
舉例來說:
n = 234
f(n) => 2 * 3 * 4 - 2+3+4= 24 - 9 =15
首先是每個digit取得可以透過 %10得到的結果
然後在用/10 去shift到下一個digit
n = 234 => check n > 0 , n % 10 = 4, n /= 10
n = 23 => check n > 0 , n % 10 = 3, n /= 10
n = 2 => check n > 0, n % 10 = 2, n /= 10
n = 0
given an integer n
step 0: let a integer sum = 0, a integer product = 1
step 1: if n <= 0 go to step 3
step 2: sum += n%10, product*= n%10, n/=10, go to step1
step 3: return product - sum
package subtract_product_sum
func subtractProductAndSum(n int) int {
sum := 0
product := 1
for n > 0 {
digit := n % 10
sum += digit
product *= digit
n /= 10
}
return product - sum
}
因為英文不是筆者母語
所以在題意解讀上 容易被英文用詞解讀給搞模糊
一開始不習慣把pseudo code寫下來
因此 不太容易把自己的code做解析
對於table driven test還不太熟析
所以對於寫test還是耗費不少時間
package subtract_product_sum
import "testing"
func Test_subtractProductAndSum(t *testing.T) {
type args struct {
n int
}
tests := []struct {
name string
args args
want int
}{
{
name: "Example1",
args: args{
n: 234,
},
want: 15,
},
{
name: "Example2",
args: args{
n: 4421,
},
want: 21,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := subtractProductAndSum(tt.args.n); got != tt.want {
t.Errorf("subtractProductAndSum() = %v, want %v", got, tt.want)
}
})
}
}